/**
 * 1、基于props，父子组件
 * 2、context
 * 3、redux
 */

/**
 * 单向数据流
 * 1、属性的传递方向是单向的
 * 父组件基于属性把信息传递给子组件
 * 子组件无法基于属性给父组件传信息，但可以把父组件传递的方法执行，从而实现子改父
 * 
 * 2、关于生命周期的延续
 * 组件第一次渲染
 *  父willMount 父render
 *  子willMount 子render 子didMount
 *  父didMount
 * 
 * 3、组件更新
 *  父shouldUpdate 父willUpdate 父render
 *  子willReciveProps 子shouldUpdate 子willUpdate 子render 子didUpdate
 *  父didUpdate
 */
import React, { useState, useCallback, useMemo, memo, createContext } from 'react';

const VoteMain = function VoteMain(props) {
    let { supNum, oppNum } = props;
    let [x, setX] = useState(0);

    let ratio = useMemo(() => {
        let total = supNum + oppNum;
        return total > 0 ? (supNum / total * 100).toFixed(2) + '%' : '--'
    })

    return <div>
        <p>支持人数： {supNum}</p>
        <p>反对人数： {oppNum}</p>
        <p>支持率： {ratio}</p>
        {x} <button onClick={() => setX(x+1)}>哈哈哈</button>
    </div>
}

const VoteFooter = memo(function VoteFooter(props) {
    let { change } = props;
    return <div>
        <button onClick={() => {change('sup')}}>支持</button>
        <button onClick={() => {change('opp')}}>反对</button>
    </div>
});

const Vote = function Vote() {
    let [supNum, setSupNum] = useState(10),
        [oppNum, setOppNum] = useState(5);
    let [num, setNum] = useState(1);

    const change = useCallback(type => {
        if (type === 'sup') {
            setSupNum(supNum + 1);
            return
        }
        setOppNum(oppNum + 1);
    }, [supNum, oppNum]);

    return <div>
        <header>
            <h2>react</h2>
            <span>{supNum + oppNum}</span>
        </header>
        <VoteMain supNum={supNum} oppNum={oppNum}></VoteMain>
        <VoteFooter change={change}></VoteFooter>
        {num} <button onClick={() => setNum(mum + 1)}>啊哈哈</button>
    </div>
}


// context
const ThemeContext = createContext();
export default ThemeContext;
function Vote() {
    return (
        <ThemeContext.Provider value={{
            name: 'zs',
            age: 10
        }}>
            <div>
                <Child></Child>
            </div>
        </ThemeContext.Provider>
    )
}
function Child() {
    const value = useContext(ThemeContext);
    return (
        <div>

        </div>
    )
}